package com.vay.de.dang.online.ui.apply;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.vay.de.dang.online.R;
import com.vay.de.dang.online.databinding.AcPhoneAuthBinding;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.entiy.RuleNotEmptyEntity;
import com.vay.de.dang.online.ui.WithBack1Activity;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.VnHandler;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.LoginApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.web.ReqResult;

public class PhoneAuthActivity extends WithBack1Activity {

    public static String facebookId;
    public static int maxErrorCount = 3;

    private AcPhoneAuthBinding binding;
    private int viewId;
    private PropertyRuleEntity rulePhone;
    private int facebookFlag;

    private boolean isOneCodeOk;
    private boolean isTwoCodeOk;

    private int countSendError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = AcPhoneAuthBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ((TextView) findViewById(R.id.title_tv)).setText(R.string.title_phone_auth);
        findViewById(R.id.bnt_back_home).setOnClickListener(view -> {
            // 业务埋点
            BaseApi.execBuriedPoint(10010, 10000,
                    "完善资料-运营商", "运营商信息返回");
            finish();
        });

        // 可以为空
        if (TextUtils.isEmpty(facebookId)) {
            facebookId = "";
        }

        // 业务埋点
        BaseApi.execBuriedPoint(10000, 10000, "运营商验证", "运营商页面可见");

        // 第一次验证码
        binding.bntOneSend.setOnClickListener(v -> {

            String phone = binding.edPhone.getText().toString();
            if (rulePhone != null) {
                RuleNotEmptyEntity notEmpty = rulePhone.getNotEmpty();
                if (notEmpty != null) {
                    if (VnUtil.isEmpty(phone)) {
                        showHint(notEmpty.getMessage());
                        return;
                    }
                }
            } else {
                if (TextUtils.isEmpty(phone)
                        || phone.length() < 9
                        || phone.length() > 10) {
                    showHint(R.string.error_phone);
                    return;
                }
            }

            // 4. facebook 验证是否成功
            if (facebookFlag == 0) {
                LoginApi.callFacebook(phone, facebookId, new ReqCallback(mActivity) {

                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {
                            facebookFlag = 1;
                            VnHandler.runUIDelayed(() -> {
                                sendFirstCode(phone);
                            }, 500);
                        }
                    }
                }.showDialog(true));
            } else {
                sendFirstCode(phone);
            }
        });

        // 第二次验证码
        binding.bntTwoSend.setOnClickListener(v -> {

            if (!isOneCodeOk) {
                showHint(R.string.label_hint_get_one_code);
                return;
            }

            String phone = binding.edPhone.getText().toString();
            String code1 = binding.edOneCode.getText().toString();
            if (TextUtils.isEmpty(code1)) {
                showHint(R.string.label_hint_input_one_code);
                return;
            }

            sendSecondCode(phone, code1);
        });

        // 验证
        binding.bntSubmit.setOnClickListener(v -> {

            String phone = binding.edPhone.getText().toString();
            String code1 = binding.edOneCode.getText().toString();

            // Vietnamobile: 验证并提交
            if (viewId == R.id.tv_yy_4) {

                if (TextUtils.isEmpty(code1)) {
                    showHint(R.string.hint_input_v_code);
                    return;
                }

                LoginApi.authByVietnamobile(phone, code1, new ReqCallback(mActivity) {
                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {
                            authSuccessful();
                        } else {
                            checkSendError();
                        }
                    }
                }.showDialog(true));
            }
            // viet,mobi,vina
            else {

                if (!isOneCodeOk) {
                    showHint(R.string.label_hint_get_one_code);
                    return;
                }

                if (!isTwoCodeOk) {
                    showHint(R.string.label_hint_get_two_code);
                    return;
                }

                String code2 = binding.edTwoCode.getText().toString();
                if (TextUtils.isEmpty(code2)) {
                    showHint(R.string.label_hint_input_two_code);
                    return;
                }

                LoginApi.authByOther(phone, code2, new ReqCallback(mActivity) {
                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {
                            authSuccessful();
                        } else {
                            checkSendError();
                        }
                    }
                }.showDialog(true));
            }
        });

        // 当时手机号码
        binding.edPhone.setText(VnContext.instance().getPhone());

        View.OnClickListener click = v -> {
            viewId = v.getId();
            updateYY();
        };
        binding.tvYy1.setOnClickListener(click);
        binding.tvYy2.setOnClickListener(click);
        binding.tvYy3.setOnClickListener(click);
        binding.tvYy4.setOnClickListener(click);

        viewId = R.id.tv_yy_1;
        updateYY();

        LoginApi.mobileRule(new ReqCallback(mActivity) {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    rulePhone = (PropertyRuleEntity) value.result;
                }
            }
        }.showDialog(true));
    }

    private void updateYY() {
        if (viewId == R.id.tv_yy_1) {
            updateYYView(binding.tvYy1, true);
            updateYYView(binding.tvYy2, false);
            updateYYView(binding.tvYy3, false);
            updateYYView(binding.tvYy4, false);
            binding.secondLayout.setVisibility(View.VISIBLE);
            countSendError = 0;
            isOneCodeOk = false;
            isTwoCodeOk = false;
        } else if (viewId == R.id.tv_yy_2) {
            updateYYView(binding.tvYy1, false);
            updateYYView(binding.tvYy2, true);
            updateYYView(binding.tvYy3, false);
            updateYYView(binding.tvYy4, false);
            binding.secondLayout.setVisibility(View.VISIBLE);
            countSendError = 0;
            isOneCodeOk = false;
            isTwoCodeOk = false;
        } else if (viewId == R.id.tv_yy_3) {
            updateYYView(binding.tvYy1, false);
            updateYYView(binding.tvYy2, false);
            updateYYView(binding.tvYy3, true);
            updateYYView(binding.tvYy4, false);
            binding.secondLayout.setVisibility(View.VISIBLE);
            countSendError = 0;
            isOneCodeOk = false;
            isTwoCodeOk = false;
        } else if (viewId == R.id.tv_yy_4) {
            updateYYView(binding.tvYy1, false);
            updateYYView(binding.tvYy2, false);
            updateYYView(binding.tvYy3, false);
            updateYYView(binding.tvYy4, true);
            binding.secondLayout.setVisibility(View.GONE);
            countSendError = 0;
            isOneCodeOk = false;
            isTwoCodeOk = false;
        }
    }

    private void updateYYView(TextView tv, boolean selected) {
        if (selected) {
            tv.setBackgroundResource(R.drawable.bg_bnt_apply);
            tv.setTextColor(Color.WHITE);
        } else {
            tv.setBackgroundResource(R.drawable.bg_bnt_no);
            tv.setTextColor(Color.parseColor("#666666"));
        }
    }

    // 获取第一次验证码,返回1表示成功
    private void sendFirstCode(String phone) {
        LoginApi.sendOneCode(phone, new ReqCallback(mActivity) {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    showHint(R.string.label_send_one_code);
                    isOneCodeOk = true;
                    binding.bntOneSend.startCountDown();
                } else {
                    showHint(R.string.label_send_one_code_error);
                    checkSendError();
                }
            }
        }.showDialog(true));
    }

    // 获取第二次验证码,返回1表示成功
    private void sendSecondCode(String phone, String oneCode) {
        LoginApi.sendSecondCode(phone, oneCode, new ReqCallback(mActivity) {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    showHint(R.string.label_send_one_code);
                    isTwoCodeOk = true;
                    binding.bntOneSend.startCountDown();
                } else {
                    showHint(R.string.label_send_one_code_error);
                    checkSendError();
                }
            }
        }.showDialog(true));
    }

    private void checkSendError() {
        countSendError++;
        if (countSendError >= maxErrorCount) {
            showHint(R.string.label_max_error_count);
            Intent intent = new Intent();
            intent.putExtra("result", 2);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private void authSuccessful() {
        Intent intent = new Intent();
        intent.putExtra("result", 1);
        setResult(RESULT_OK, intent);
        finish();
    }
}
